import bus from '@/store/bus.js'
import { v4 as uuidv4 } from "uuid";
import CryptoJS from 'crypto-js';
let urlTestV4 = 'http://127.0.0.1:996/'
let urlProV4 = 'https://v5api.sanzhiyun.cn/'
// eslint-disable-next-line no-undef
let baseUrlV4 = process.env.NODE_ENV ==='development' ? urlTestV4 : urlProV4
import axios from "axios";
import { ElMessage, ElMessageBox  } from 'element-plus';
import serialize from './obj2str'
import xe from 'xe-utils'
import dayjs from "dayjs";
import weekday from 'dayjs/plugin/weekday'
import 'dayjs/locale/zh-cn'
import Cookies from "js-cookie";
dayjs.extend(weekday)
dayjs.locale('zh-cn')
let tool = {
    xe: xe,
    dayjs: dayjs,
}
tool.data = {
    set(key, data) {
        localStorage.setItem(key, JSON.stringify(data))
    },
    get(key) {
        try {
            return JSON.parse(localStorage.getItem(key))
        } catch (err) {
            return null
        }
    },
    remove(key) {
        return localStorage.removeItem(key)
    },
    clear() {
        return localStorage.clear()
    },
    getTenantId () {
        let usr = tool.data.getUser()
        if(usr) {
            return usr.tenantId
        }
        return null
    },
    getUser () {
        let usr = tool.data.get("v3UserInfo")
        if(usr) {
            return usr
        }
        return null;
    },
    getUserId () {
        let usr = tool.data.getUser()
        return usr ? usr.id : null;
    },
    getUserName () {
        let usr = tool.data.getUser()
        return usr ? usr.name : null;
    },
    logout() {
        tool.data.remove("v3UserInfo");
        tool.data.remove("TOKEN");
        tool.data.remove("itemStore");
    },
    setUser (data) {
        tool.data.set('v3UserInfo', data)
        tool.data.set('TOKEN', data.token)
    },
}
tool.Session = {
    // 设置临时缓存
    set(key, val) {
        if (key === 'token') return Cookies.set(key, val);
        window.sessionStorage.setItem(key, JSON.stringify(val));
    },
    // 获取临时缓存
    get(key) {
        if (key === 'token') return Cookies.get(key);
        let json = window.sessionStorage.getItem(key);
        return JSON.parse(json);
    },
    // 移除临时缓存
    remove(key) {
        if (key === 'token') return Cookies.remove(key);
        window.sessionStorage.removeItem(tool.data.setKey(key));
    },
    // 移除全部临时缓存
    clear() {
        Cookies.remove('token');
        window.sessionStorage.clear();
    },
}
tool.add = (...vars) => {
    let len = vars.length
    let sum = 0
    for (let i = 0; i < len; i++) {
        sum = xe.add(sum,vars[i])
    }
    return sum
}
tool.minus = (...vars) => {
    let len = vars.length
    let sum = vars[0]
    for (let i = 1; i < len; i++) {
        sum = xe.subtract(sum,vars[i])
    }
    return sum
}
tool.divide = (...vars) => {
    let len = vars.length
    let sum = vars[0]
    for (let i = 1; i < len; i++) {
        sum = xe.divide(sum,vars[i])
    }
    return sum
}
tool.multiply = (...vars) => {
    let len = vars.length
    let sum = vars[0]
    for (let i = 1; i < len; i++) {
        sum = xe.multiply(sum,vars[i])
    }
    return sum
}
// 组合列表显示 的字段
tool.info = (msg) => {
    ElMessage.info(msg)
}
tool.suc = (msg) => {
    ElMessage.success(msg)
}
tool.err = (msg) =>{
    ElMessage.error(msg)
}
tool.warning = (msg) =>{
    ElMessage.warning(msg)
}
tool.confirm = (msg, title = '删除提醒', load) => {
    return new Promise((resolve) => {
        ElMessageBox.confirm(msg, title, {draggable: true,}).then(() => {
            resolve()
        }).catch(() => {
            if(typeof load !== 'undefined') {
                load.loading = false
            }
        })
    })
}
// 关闭loading层
tool.hide = (timeout = 10) => {
    setTimeout(() => {
        bus.$emit('loading', false)
    }, timeout)
}
// 显示 页面加载
tool.loading = () => {
    bus.$emit('loading', true)
}
tool.uuid = () => {
    return uuidv4();
}
tool.crypto = {
    //MD5加密
    MD5(data){
        return CryptoJS.MD5(data).toString()
    },
}
tool.post =  (url, data = {}, load) => {
    data.ter = 'pc'
    let userInfo = tool.data.getUser()
    let token = userInfo ? userInfo.token : ''
    postLoading(load, true)

    return axios.post(url, data, {baseURL: baseUrlV4, headers: {token: token ? token : '', 'Content-Type': 'application/json'}})
        .then(ret => {
            if (ret && ret.data) {
                let data = ret.data
                if (data.stat && data.msg)  {
                    tool.suc(data.msg)
                }
                if (!data.stat && data.msg)  {
                    tool.err(data.msg)
                }
                return Promise.resolve(data)
            } else {
                tool.err('读取失败')
                return Promise.resolve(false)
            }

        })
        .catch(errs => {
            let r = errs.response
            if (r && r.status && r.status === 401) {
                if (r.data && r.data.msg) {
                    tool.err(r.data.msg)
                }
            }
            return Promise.resolve(false)
        })
        .finally(() => {
            postLoading(load, false)
        })
}
// --     case when a.transType in(150601,150602,150603,150806) then b.lastPrice else 0 end costPrice,
//   --                                case when a.transType in(150601,150602,150603,150806) then round(a.outCount*b.lastPrice,2) else 0 end costMoney
// --     case when a.transType in(150501,150706,150502) then
// --                                         iif(a.lastCount=0,b.lastPrice,round(a.inMoney+b.lastMoney,2)/a.lastCount)
// --                                     when a.transType in(150601,150602,150603,150806) then
// --                                         iif(b.lastCount-a.outCount=0,b.lastPrice,(b.lastMoney-round(a.outCount*b.lastPrice,2))/(b.lastCount-a.outCount))
// -- end lastPrice,
//

const postLoading = (load, val) => {
    if(typeof load === 'boolean') {
        if(load) {
            if (val) {
                bus.$emit('doLoading', val)
            }
            else {
                bus.$emit('doLoading', val)
            }
            setTimeout(() => {
                bus.$emit('doLoading', false)
            }, 20000)
        }
    }
    else if(typeof load === 'object') {
        if(!xe.isEmpty(load)) {
            if (val) {
                load.loading = val
            }
            else {
                load.loading = val
            }
            setTimeout(() => {
                load.loading = false
            }, 20000)
        }
    }
}
// 时间加减方法
// 时间加减方法
tool.getDay = (day= '', diff = 0, addType = 'day', format = 'YYYY-MM-DD') => {
    return dayjs(day?day:dayjs()).add(diff, addType).format(format)
}
tool.dateFormat = (day, format = 'YYYY-MM-DD') => {
    return  dayjs(day?day:dayjs()).format(format)
}
tool.datetime = (day, format = 'YYYY-MM-DD HH:mm:ss') => {
    return  dayjs(day?day:dayjs()).format(format)
}
// type = beg|end 开始日期|结束日期,diff 加减数量,unit MONTH|DAY|YEAR  current 当前时间
tool.getDayStart = (current = '', type = 'beg', diff = 0, unit = 'MONTH') => {
    if (type === 'beg'){
        return   dayjs(current ? current : dayjs()).add(diff, unit).startOf(unit).format('YYYY-MM-DD')
    }
    if (type === 'end'){
        return   dayjs(current ? current : dayjs()).add(diff, unit).endOf(unit).format('YYYY-MM-DD')
    }
}
//
tool.getBillState = () => {
    return [
        {id:'draft', name: '草稿'},
        {id:'accounted', name: '已记账'},
        {id:'del', name: '已删除'},
        {id:'all', name: '全部'},
    ]
}
tool.toolbarAction = (acs = []) => {
    let btn = [
        {name: '新增', code: 'addNew',type: 'text', icon: 'fa fa-plus'},
        {name: '增加', code: 'add',type: 'text', icon: 'fa fa-plus'},
        {name: '记账', code: 'accounted',type: 'text', icon: 'fa fa-rmb',status: 'danger'},
        {name: '编辑', code: 'billEdit', type: 'text',icon: 'fa fa-edit'},
        {name: '重置路线', code: 'resetArea', icon: 'fa fa-map',type: 'text',status: 'danger'},
        {name: '删除', code: 'del',type: 'text', icon: 'fa fa-trash'},
        {name: '打印预览', code: 'printView',type: 'text', icon: 'fa fa-eye'},
        {name: '直接打印', code: 'print',type: 'text', icon: 'fa fa-print'},
        {name: '导数据',icon: 'fa fa-file-o',size: 'small',type: 'text', dropdowns: [
                {name:  '导入数据',size: 'small', code: 'doImport', icon: 'fa fa-cloud-upload'},
                {name:   '下载模板',size: 'small',code: 'downloadMoban', icon: 'fa fa-file-o'}
            ]
        },
        {name: '刷新', code: 'refresh',type: 'text', icon: 'fa fa-refresh'},
    ]
    let arr = []
    for (let i = 0; i < acs.length; i++) {
        for (let j = 0; j < btn.length; j++) {
            if (acs[i] === btn[j].name) {
                arr.push(btn[j])
            }
        }
    }
    return arr
}
tool.toPrint = (printList, direct = false, isCard = false) => {
    if (printList.length === 0) return tool.err('至少选择 1 行记录进行操作')
    let ids = []
    for (let i = 0; i < printList.length; i++) {
        ids.push(printList[i].id)
    }
    if(ids.length > 20) return tool.err('不能批量打印超过 20 条数据')
    // eslint-disable-next-line no-undef
    const LODOP = (typeof getCLodop==='function') ? getCLodop() : ''
    if (!LODOP) {
        tool.post('common/getPrintUrl', {}).then(ret => {
            if(ret.stat) {
                window.location.href = ret.data
            }
        })
        return tool.info('正在下载打印控件,下载完成后请解压并安装。')
    }
    LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
    LODOP.SET_LICENSES("","C748D766DD08B5AE84E6BC2F3A546E6C7C9","","");
    tool.post('print/getPrint', {ids: ids , isCard: isCard,direct: false}).then(ret => {
        if (ret.stat) {
            let data = ret.data
            let evals = data.evals
            let taskId = data.task_id
            for (let i = 0; i < evals.length; i++) {
                if (evals[i].str) {
                    eval(evals[i].str)
                }
                else {
                    LODOP.ADD_PRINT_TABLE(0,15,'96%','100%', evals[i].data)
                }
            }
            if (LODOP.CVERSION){
                LODOP.On_Return = (TaskID, Value)=> {
                    if(Value === true || tool.xe.toNumber(Value) === 1)
                        tool.post('print/printSuc', {taskId: taskId}, false).then(() => {})
                    // let strResult = LODOP.GET_VALUE('PRINT_STATUS_EXIST')
                }
                if (direct) {
                    LODOP.PRINT()
                }
                else {
                    LODOP.PREVIEW()
                }
            }
        }
    })
}

tool.toArrayTree = (ret) => {
    ret.map(row => {
        row.pid = row.pid ? row.pid : null
    })
    return xe.toArrayTree(ret, { parentKey: "pid", strict: true });
}
tool.toTreeArray = (ret) => {
    return xe.toTreeArray(ret, { clear: true });
}
// 组合查询条件
tool.setSearch = (formData, searchRule) => {
    let where = []
    for (let i in formData) {
        if (i && formData[i]) {
            searchRule.map(s => {
                if (s.field === i) {
                    let sop = s.sop ? s.sop : '='
                    if (sop === 'include') {
                        where.push(` ${i} like '%${formData[i]}%' `)
                    }
                    else {
                        if(s.dataType) {
                            if(s.dataType === 'string') {
                                if(s.realField) {
                                    where.push(` ${s.realField} ${s.sop} '${formData[i]}' `)
                                }
                                else {
                                    where.push(` ${i} ${s.sop} '${formData[i]}' `)
                                }
                            }
                        }
                        else {
                            where.push(` ${i} ${s.sop} ${formData[i]} `)
                        }
                    }
                }
            })
        }
    }
    return where
}
// 获取地址 经纬度
tool.getLngLat = (callback) => {

}

tool.obj2str = serialize
tool.str2obj = (str) => {
    return new Function('return ' + str)()
}

tool.billToRoute = (billNo) => {
    if(billNo.indexOf('SK') === 0) {
        return 'receipt'
    }
    if(billNo.indexOf('XS') === 0) {
        return 's-in'
    }
    if(billNo.indexOf('XT') === 0) {
        return 's-out'
    }
    if(billNo.indexOf('XH') === 0) {
        return 's-t'
    }
    if (billNo.indexOf('FK') === 0) {
      return 'payment'
    }
    if(billNo.indexOf('CG') === 0) {
        return 'pur-in'
    }
    if(billNo.indexOf('CT') === 0) {
        return 'pur-out'
    }
    return false
}

// 弹出查看明细
tool.openPage = (row, field, route, router) => {
    // 取路由
    tool.post('page/getRouteByField', {
        field,
        routeName: route.name,
        value: row[field],
        row,
    })
        .then(ret => {
        if(ret.stat) {
            let routeName = ret.data.name
            // let par = {
            //     title: ret.data.title ? ret.data.title : '明细',
            //     url: window.location.origin + routeName,
            //     showMax: true,
            //     showToggle: true,
            //     showMin: true,
            //     isResize: true,
            //     slide: false,
            //     modal: false,
            //     width: ret.data.width ? ret.data.width : 800,
            //     height: ret.data.height ? ret.data.height : 800,
            //     data: {field, ...ret.data.query}
            // }
            // if(left) par.left = left
            // if(top) par.top = top
            tool.data.set('query', ret.data.query)
            router.push({name: routeName})
            // eslint-disable-next-line no-undef
            // $.ligerDialog.open(par)
        }
    })
}
tool.openEdit = (data = {}) => {
    let title = data.title ? data.title : ''
    let id = 0
    if(data.row) {
        id = data.row.id
    }
    title = id ? '编辑 ' + title : '新增 '  + title
    bus.$emit('openEdit', {
        title,
        params: data
    })
}

tool.toAssQty = (row) => {
    let m = Math.floor(row.qty/row.spec)
    let m2 = row.qty%row.spec
    let ass = ''
    if(m > 0) {
        ass += m+row.unit1
    }
    if(m2 > 0) {
        ass += ' ' + m2+row.unit2
    }
    return ass
}

tool.getMenuList = async () => {
   let ret = await tool.post('user/getMenuList', {})
    let data = ret.data
    let menu = {
        id: -1,
        pid: 0,
        sort: 12,
        icon: 'star-off',
        name: '常用',
        display: 1
    }
    if (data && data.length > 0) {
        data.splice(0,0,menu)
        // let menuList = tool.data.get('jsonMenu')
    }
    return data
}



export default tool
